package com.ityueqiangu.portal.conroller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.ityueqiangu.system.domain.Carousel;
import com.ityueqiangu.system.service.ICarouselService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Clever、xia
 * @title: IndexController
 * @projectName art-exhibition-system
 * @description:
 * @date 2021-03-10 21:40
 */
@Controller
@RequestMapping(value = "/portal")
public class PortalController {

    @Autowired
    private ICarouselService carouselService;

    @RequestMapping(value = "/index")
    public String index(){
        return "portal/index";
    }

    @RequestMapping(value = "/login")
    public String login(){
        return "portal/login";
    }

    @RequestMapping(value = "/register")
    public String register(){
        return "portal/register";
    }

    @RequestMapping(value = "/indexNew")
    public String indexNew(ModelMap mmap){
        List<Carousel> carousels = carouselService.selectCarouselList(new Carousel());
        //按照sortno排序
        carousels = carousels.stream().sorted(Comparator.comparing(Carousel::getSortNo)).collect(Collectors.toList());
        mmap.addAttribute("carousels",carousels);
        return "front/index";
    }

    @RequestMapping(value = "/exhibitionDetail")
    public String exhibitionDetail(){
        return "front/exhibitionDetail";
    }



    @RequestMapping(value = "/getRandomImage")
    public void getRandomImage(HttpServletRequest request, HttpServletResponse response){
        RandomGenerator randomGenerator = new RandomGenerator("0123456789abcdefghklmnpqrstxyzABCDEFGHKLMNPQRSTXYZ", 4);
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);
        captcha.setGenerator(randomGenerator);
        //得到code
        String code = captcha.getCode();
        System.out.println(code);
        //放到session
        request.getSession().setAttribute("randomImage", code);
        //输出流
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //读写输出流
            captcha.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭输出流
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
